package com.yunkaweilai.android.fragment;

/*
 订单/退款界面
 */

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.web.WebActivity;
import com.yunkaweilai.android.activity.web.WebActivityWithRufund;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.home.RecordListBean;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.MyToast;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.SinglePicker;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;


public class OrderFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener, BGARefreshLayout.BGARefreshLayoutDelegate {

    private TitleBuilder titleBuilder;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_listView)
    ListView ListView;
    @BindView(R.id.radiogroup_order)
    RadioGroup mRadioGroup;
    @BindView(R.id.radio_order_1)
    RadioButton mIdRbtn1;
    @BindView(R.id.radio_order_2)
    RadioButton mIdRbtn2;
    @BindView(R.id.radio_order_3)
    RadioButton mIdRbtn3;
    @BindView(R.id.radio_order_4)
    RadioButton mIdRbtn4;
    @BindView(R.id.radio_order_5)
    RadioButton mIdRbtn5;
    @BindView(R.id.id_edt_search)
    EditText mEditText;
    @BindView(R.id.orderfragment_Choose_TextView)
    TextView mTextView;

    private int radio_position = 0;
    private CommonAdapter<RecordListBean.data.list> Adapter;
    private List<RecordListBean.data.list> mList = new ArrayList<>();
    private boolean is_pay = false;
    private boolean is_gift = false;
    private boolean is_refund = false;
    private String type_id;
    public static final String TYPE_ID_XIAOFEI = "15";  //消费记录
    public static final String TYPE_ID_CHARGE = "17";   //充值记录
    public static final String TYPE_ID_SCORE = "21";    //积分记录
    public static final String TYPE_ID_SCORE_CHANGE = "22"; //积分兑换记录
    public static final String TYPE_ID_REFUND = "23";   //退款记录
    private boolean next = true;//判断是否有下一页
    private int currpage = 1; //获取第几一页的数据
    private String keyword = "";
    private String days = "7";

    @Override
    public int getContentViewId() {
        return R.layout.fragment_order;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initTitle(rootView);
        mRadioGroup.setOnCheckedChangeListener(this);

        initAdapter();
        initview();
        initRefreshLayout(contentView, this, true); //使控件能够刷新
        initHttp(true);
        return rootView;
    }


    private void initview() {
        ListView.setAdapter(Adapter);
        setRadio_position(radio_position);
        idMultipleStatusView.showLoading();
        initTextView();//初始化下拉框
        // 设置输入框的点击事件
        mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                keyword = mEditText.getText().toString();
                contentView.beginRefreshing();
                return true;
            }
        });
    }

    private void initTextView() {
        final String[] Items = {"7天", "15天", "30天"};//下拉框选项
        final String[] Items2 = {"7", "15", "30"}; //下拉框选项对应的inithttp传值
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SinglePicker<String> picker = new SinglePicker<>(mAc, Items);
                picker.setCanLoop(false);//不禁用循环
                picker.setLineVisible(true);
                picker.setShadowVisible(true);
                picker.setTextSize(18);
                picker.setSelectedIndex(0);
                picker.setWheelModeEnable(true);
                //启用权重 setWeightWidth 才起作用
                picker.setWeightEnable(true);
                picker.setWeightWidth(1);
                picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
                picker.setUnSelectedTextColor(0xFF999999);
                picker.setOnItemPickListener(new OnItemPickListener<String>() {
                    @Override
                    public void onItemPicked(int index, String item) {
                        days = Items2[index];
                        mTextView.setText(item);
                        contentView.beginRefreshing();
                    }
                });
                picker.show();
            }
        });


    }

    public void refresh() {
//        initHttp(true);
        contentView.beginRefreshing();
    }

    @OnClick(R.id.orderfragment_btn_search)
    void search() {
        keyword = mEditText.getText().toString();
        contentView.beginRefreshing();
    }

    private void setRadio_position(int position) {
        switch (position) {
            case 0:
                mIdRbtn1.setChecked(true);
                break;
            case 1:
                mIdRbtn2.setChecked(true);
                break;
            case 2:
                mIdRbtn3.setChecked(true);
                break;
            case 3:
                mIdRbtn4.setChecked(true);
                break;
            case 4:
                mIdRbtn5.setChecked(true);
                break;
        }
    }


    //设置刷新的时候不能点击 刷新完成后可以点击
    private void clickable() {
        mIdRbtn1.setClickable(true);
        mIdRbtn2.setClickable(true);
        mIdRbtn3.setClickable(true);
        mIdRbtn4.setClickable(true);
        mIdRbtn5.setClickable(true);
    }

    private void unclickable() {
        mIdRbtn1.setClickable(false);
        mIdRbtn2.setClickable(false);
        mIdRbtn3.setClickable(false);
        mIdRbtn4.setClickable(false);
        mIdRbtn5.setClickable(false);
    }

    /**
     * 分五种类型 消费记录 充值记录 积分记录 积分兑换记录 退款记录
     * 不算商品行数  4        4       3          3         5
     */
    private void initAdapter() {
        Adapter = new CommonAdapter<RecordListBean.data.list>(mAc, R.layout.item_list_order_home, mList) {
            @Override
            protected void convert(ViewHolder viewHolder, final RecordListBean.data.list item, int position) {

                viewHolder.setVisible(R.id.item_list_order_home_line1, false);
                viewHolder.setVisible(R.id.item_list_order_home_line2, false);
                viewHolder.setVisible(R.id.item_list_order_home_line3, false);
                viewHolder.setVisible(R.id.item_list_order_home_line4, false);
                viewHolder.setVisible(R.id.item_list_order_home_line5, false);
                viewHolder.setVisible(R.id.item_list_order_home_line6, false);
                viewHolder.setVisible(R.id.order_view_bottom, false);
                viewHolder.setVisible(R.id.line1_right_refund, false);

                //line1 && line5(退单)
                if (type_id.equals(TYPE_ID_XIAOFEI) || type_id.equals(TYPE_ID_CHARGE) || type_id.equals(TYPE_ID_SCORE_CHANGE) || type_id.equals(TYPE_ID_REFUND)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line1, true);
                    viewHolder.setText(R.id.line1_left, "订单编号");
                    viewHolder.setText(R.id.line1_right, item.getTid());
                }
                if (type_id.equals(TYPE_ID_REFUND)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line5, true);
                    viewHolder.setText(R.id.line5_left, "退单编号");
                    viewHolder.setText(R.id.line5_right, item.getRefund_tid());
                }
                if (type_id.equals(TYPE_ID_XIAOFEI) || type_id.equals(TYPE_ID_CHARGE)) {
                    if (item.isRefund()) {
                        viewHolder.setVisible(R.id.line1_right_refund, true);
                    }
                }

                //line2
                viewHolder.setVisible(R.id.item_list_order_home_line2, true);
                if (item.getMember_id() == null) {
                    viewHolder.setText(R.id.line2_left, "散客");
                } else if (item.getMember_id().equals("0")) {
                    viewHolder.setText(R.id.line2_left, "散客");
                } else {
                    viewHolder.setText(R.id.line2_left, item.getMember_name() + "(" + item.getLevel_name() + item.getCard_no() + ")");
                }
                if (type_id.equals(TYPE_ID_XIAOFEI) || type_id.equals(TYPE_ID_CHARGE) || type_id.equals(TYPE_ID_SCORE_CHANGE)) {
                    viewHolder.setText(R.id.line2_right, item.getConsume_time());
                } else if (type_id.equals(TYPE_ID_SCORE)) {
                    viewHolder.setText(R.id.line2_right, item.getCreate_time());
                } else if (type_id.equals(TYPE_ID_REFUND)) {
                    viewHolder.setText(R.id.line2_right, item.getRefund_time());
                }

                //line3
                if (type_id.equals(TYPE_ID_XIAOFEI)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line3, true);
                    viewHolder.setText(R.id.line3_left, "消费类型");
                    viewHolder.setText(R.id.line3_right, item.getStrconsume_type());
                } else if (type_id.equals(TYPE_ID_CHARGE)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line3, true);
                    viewHolder.setText(R.id.line3_left, "充值类型");
                    viewHolder.setText(R.id.line3_right, item.getStrrecharge_type());
                } else if (type_id.equals(TYPE_ID_SCORE)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line3, true);
                    viewHolder.setText(R.id.line3_left, "积分变动");
                    viewHolder.setText(R.id.line3_right, item.getPoints() + "(" + item.getSource() + ")");
                } else if (type_id.equals(TYPE_ID_SCORE_CHANGE)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line3, true);
                    viewHolder.setText(R.id.line3_left, "积分变动");
                    viewHolder.setText(R.id.line3_right, item.getStrPoints());
                } else if (type_id.equals(TYPE_ID_REFUND)) {//如果是散客，不显示扣除积分
                    if (item.getMember_id() == null) {
                    } else if (item.getMember_id().equals("0")) {
                    } else {
                        viewHolder.setVisible(R.id.item_list_order_home_line3, true);
                        viewHolder.setText(R.id.line3_left, "扣除积分");
                        viewHolder.setText(R.id.line3_right, item.getRefund_order_points());
                    }
                }

                //line4
                if (type_id.equals(TYPE_ID_XIAOFEI) || type_id.equals(TYPE_ID_CHARGE)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line4, true);

                    if (type_id.equals(TYPE_ID_CHARGE) && item.getStrrecharge_type() != null) {
                        if (item.getStrrecharge_type().equals("储值充值") || item.getStrrecharge_type().equals("微信自助充值")) {
                            viewHolder.setText(R.id.line4_left, "实收/赠送");
                        } else if (item.getStrrecharge_type().equals("微信自助计次充值")) {
                            viewHolder.setText(R.id.line4_left, "实收");
                        } else {
                            viewHolder.setText(R.id.line4_left, "应收/实收");
                        }
                    } else {
                        viewHolder.setText(R.id.line4_left, "应收/实收");
                    }

                    //计次消费的储值支付，显示卡内扣除
                    if (item.getStrconsume_type() != null && item.getPayment_type() != null && item.getStrconsume_type().equals("计次消费") && item.getPayment_type().equals("储值支付")) {
                        viewHolder.setText(R.id.line4_right, "卡内扣除");
                    } else if (item.getStrrecharge_type() != null && item.getPayment_type() != null && (item.getStrrecharge_type().equals("储值充值") || item.getStrrecharge_type().equals("微信自助充值"))) {
                        float x1 = Float.parseFloat(item.getZ_goods_price()) - Float.parseFloat(item.getS_payment());
                        DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                        String p = decimalFormat.format(x1);//format 返回的是字符串
                        viewHolder.setText(R.id.line4_right, item.getZ_discount_price() + "/" + p + "(" + item.getPayment_type() + ")");
                    } else if (item.getStrrecharge_type() != null && item.getPayment_type() != null && item.getStrrecharge_type().equals("微信自助计次充值")) {
                        viewHolder.setText(R.id.line4_right, item.getS_payment() + "(" + item.getPayment_type() + ")");
                    } else {
                        viewHolder.setText(R.id.line4_right, item.getZ_discount_price() + "/" + item.getS_payment() + "(" + item.getPayment_type() + ")");
                    }
                } else if (type_id.equals(TYPE_ID_SCORE)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line4, true);
                    viewHolder.setText(R.id.line4_left, "变动后积分");
                    viewHolder.setText(R.id.line4_right, item.getX_points());
                } else if (type_id.equals(TYPE_ID_REFUND)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line4, true);
                    viewHolder.setText(R.id.line4_left, item.getRefund_content());

                    if (item.getRefund_content() == null) {
                        viewHolder.setText(R.id.line4_right, "");
                    } else if (item.getRefund_content().equals("退还现金")) {
                        viewHolder.setText(R.id.line4_right, item.getRefund_cash() + "元");
                    } else if (item.getRefund_content().equals("退还余额")) {
                        viewHolder.setText(R.id.line4_right, item.getRefund_balance() + "元");
                    } else if (item.getRefund_content().equals("退还支付宝")) {
                        viewHolder.setText(R.id.line4_right, item.getRefund_alipay() + "元");
                    } else if (item.getRefund_content().equals("退还微信")) {
                        viewHolder.setText(R.id.line4_right, item.getRefund_wechat() + "元");
                    } else if (item.getRefund_content().equals("其他退还")) {
                        viewHolder.setText(R.id.line4_right, item.getRefund_other());
                    } else {
                        viewHolder.setText(R.id.line4_right, "");
                    }

                }

                //line6
                if (type_id.equals(TYPE_ID_XIAOFEI) || type_id.equals(TYPE_ID_CHARGE)) {
                    if (item.getStrGoodsList() != null && item.getStrGoodsList().equals("无商品")) {

                    } else {
                        viewHolder.setVisible(R.id.order_view_bottom, true);
                        viewHolder.setVisible(R.id.item_list_order_home_line6, true);
                        viewHolder.setText(R.id.line6_left, item.getStrGoodsList());
                    }
                }
                if (type_id.equals(TYPE_ID_SCORE_CHANGE)) {
                    viewHolder.setVisible(R.id.item_list_order_home_line6, true);
                    viewHolder.setText(R.id.line6_left, item.getStrGiftList());
                }
                if (type_id.equals(TYPE_ID_REFUND)) {
                    viewHolder.setVisible(R.id.order_view_bottom, true);
                    viewHolder.setVisible(R.id.item_list_order_home_line6, true);
                    viewHolder.setText(R.id.line6_left, item.getRefund_remark());
                }

                //点击事件
                LinearLayout idLlayoutItem = viewHolder.getView(R.id.id_llayout_item);
                idLlayoutItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (type_id) {
                            case TYPE_ID_XIAOFEI:
                                WebActivityWithRufund.actionStart(mAc, Api.BASE_URL + "index.php/app/OrderInfoView.html?tid=" + item.getTid() +
                                        "&token=" + BaseApplication.getToken(), Api.BASE_URL + "index.php/app/newOrderRefundView.html?tid=" + item.getTid() +
                                        "&token=" + BaseApplication.getToken());
                                break;
                            case TYPE_ID_CHARGE:
                                WebActivityWithRufund.actionStart(mAc, Api.BASE_URL + "index.php/app/RechargeInfoView.html?tid=" + item.getTid()
                                        + "&token=" + BaseApplication.getToken(), Api.BASE_URL + "index.php/app/newOrderRefundView.html?tid=" + item.getTid()
                                        + "&token=" + BaseApplication.getToken());
                                break;
                            case TYPE_ID_REFUND:
                                WebActivity.actionStart(mAc, Api.BASE_URL + "index.php/app/OrderInfoView.html?tid=" + item.getTid() +
                                        "&token=" + BaseApplication.getToken());
                                break;
                        }
                    }
                });
                //
                if (is_pay) {

                }
                if (is_gift) {

                }
                if (is_refund) {
                }

            }
        };
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.radio_order_1:
                type_id = TYPE_ID_XIAOFEI;
                keyword = "";
                mEditText.setText("");
                contentView.beginRefreshing();//开始刷新
                break;
            case R.id.radio_order_2:
                type_id = TYPE_ID_CHARGE;
                keyword = "";
                mEditText.setText("");
                contentView.beginRefreshing();
                break;
            case R.id.radio_order_3:
                type_id = TYPE_ID_SCORE;
                keyword = "";
                mEditText.setText("");
                contentView.beginRefreshing();
                break;
            case R.id.radio_order_4:
                type_id = TYPE_ID_SCORE_CHANGE;
                keyword = "";
                mEditText.setText("");
                contentView.beginRefreshing();
                break;
            case R.id.radio_order_5:
                type_id = TYPE_ID_REFUND;
                keyword = "";
                mEditText.setText("");
                contentView.beginRefreshing();
                break;
        }
    }

    //设置标题
    private void initTitle(View rootView) {
        titleBuilder = new TitleBuilder(rootView)
//                .setLeftImage(R.mipmap.ic_go_back)
                .setTitleText(getResources().getString(R.string.tab_main_2))
//                .setRightText("新增")
        ;
    }

    private boolean initHttp(final boolean refresh) {
        unclickable();
        currpage = refresh ? 1 : currpage; //ture的时候重新加载 不然就是++后的结果
        if ((!next) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            clickable();
            return false;
        }
        HttpRequest.postUrl(Api.APP_RECORD_LIST)
                .addParams("type_id", type_id)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", "" + currpage)
                .addParams("days", days)
                .addParams("keyword", keyword)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            currpage++;

                            RecordListBean recordListBean = new RecordListBean();
                            recordListBean = gson.fromJson(json, RecordListBean.class);
                            if (refresh) {//第一页加载就清空
                                mList.clear();
                            }
                            mList.addAll(recordListBean.getData().getList());

                            next = recordListBean.getData().getPage().isNext();
                            is_pay = recordListBean.getData().isIs_pay();
                            is_gift = recordListBean.getData().isIs_gift();
                            is_refund = recordListBean.getData().isIs_refund();

                            Adapter.notifyDataSetChanged();
                            if (refresh){
                                ListView.smoothScrollToPosition(0);
                            }
                            if (mList.isEmpty() && idMultipleStatusView != null) {
                                idMultipleStatusView.showEmpty();   // 展示全空视图
                            } else {
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();// 展示内容
                                }
                            }
                        }
                        clickable();
                    }

                    @Override
                    public void onError(Exception e) {
                        MyToast.showShortToast(mAc, e.getMessage());
                        clickable();
                    }
                });
        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        contentView.beginRefreshing();
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }
}
